//
//  ViewController.m
//  19-JSON
//
//  Created by Snow on 16/8/9.
//  Copyright © 2016年 Snow. All rights reserved.
//

#import "ViewController.h"
#import "TitleCollectionViewCell.h"
#import "MyLayout.h"
#import "ContentTitle.h"

@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, GXLabelWidth>
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;
@property (nonatomic, strong) NSMutableArray<ContentTitle *> *contentTitleArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self handelData];
    MyLayout *layout = (MyLayout *)self.myCollectionView.collectionViewLayout;
    layout.delegate = self;
}
- (void)handelData
{
    self.contentTitleArray = [NSMutableArray array];
    //JSON 解析
    //通过一个data, 将对应的JSON格式转换成OC认识的内容
    //数组/字典
    NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"FirstJSON" ofType:@"json"];
    NSData *jsonData = [NSData dataWithContentsOfFile:dataPath];
    //json 解析
    NSError *error = nil;
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    NSArray *list = jsonDic[@"tabs"][@"list"];
    for (NSDictionary *contentDic in list) {
        ContentTitle *contentTitle = [ContentTitle contentTitleWithDictionary:contentDic];
        [_contentTitleArray addObject:contentTitle];
    }
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _contentTitleArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TitleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.contentTitle = [_contentTitleArray objectAtIndex:indexPath.row];
    return cell;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout height:(CGFloat)height heightForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ContentTitle *contentTitle = [_contentTitleArray objectAtIndex:indexPath.row];
    CGRect newRect = [contentTitle.title boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 40) options:1 attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
    CGFloat width = ceilf(CGRectGetWidth(newRect));
    return width;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
